#include "UControlContainer.h"
#include "Controls/UControl.h"

TControlContainer::TControlContainer()
{
	ActiveControlIndex = 0;
	MousePosControl = NULL;
	LastClickControl = NULL;
}

void TControlContainer::KeyDown(SDL_KeyboardEvent* Key)
{
	if (ActiveControl()!=NULL)
		ActiveControl()->KeyDown(Key);
}

void TControlContainer::KeyUp(SDL_KeyboardEvent* Key)
{
	if (ActiveControl()!=NULL)
		ActiveControl()->KeyUp(Key);
}


void TControlContainer::MouseMove(int X, int Y, int mstate)
{
	for (size_t i=0; i < Controls.size(); ++i)
	{
		if (Controls[i]->Contains(X, Y) || (ActiveControl()==Controls[i])  ) {
			if (MousePosControl!=NULL && MousePosControl!=Controls[i])
				MousePosControl->MouseLeave();
			Controls[i]->MouseMove(X, Y, mstate);
			MousePosControl = Controls[i];
		}
	}
	
	if (MousePosControl!=NULL && !MousePosControl->Contains(X, Y)) {
		MousePosControl->MouseLeave();
		MousePosControl = NULL;
	}


}

void TControlContainer::MouseDown(int X, int Y, uint8 button)
{
	for (size_t i=0; i < Controls.size(); ++i)
	{
		if (Controls[i]->Contains(X, Y))
		{
			ActiveControlIndex = i;
			Controls[i]->MouseDown(X, Y, button);
			LastClickControl = Controls[i];
		}
	}
}

void TControlContainer::MouseUp(int X, int Y, uint8 button)
{
	if (LastClickControl != NULL && !LastClickControl->Contains(X, Y))
		LastClickControl->MouseUp(X, Y, button);

	for (size_t i=0; i < Controls.size(); ++i)
	{
		if (Controls[i]->Contains(X, Y))
			Controls[i]->MouseUp(X, Y, button);
	}
	
	LastClickControl = NULL;
}

void TControlContainer::MouseLeave()
{
	if (MousePosControl !=NULL) {
		MousePosControl->MouseLeave();
		MousePosControl = NULL;
	}
}

void TControlContainer::Draw( )
{
	for (size_t i=0; i < Controls.size(); ++i)
	{
		// next line a bit of a hax, till the new focus approach is fully implemented
		Controls[i]->setFocus(ActiveControlIndex == i);
		if (Controls[i]->visible)
			Controls[i]->Draw();
	}
}

TControl* TControlContainer::ActiveControl()
{
	return GetControl(ActiveControlIndex);
}

void TControlContainer::AddControl(TControl* control)
{
	Controls.push_back(control);
}

TControl* TControlContainer::GetControl(size_t index)
{
	if (index < 0) return NULL;
	if (index >= Controls.size()) return NULL;
	return Controls[index];
}

